package com.leyou.item.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.item.pojo.Stock;
import com.leyou.item.service.CategoryService;
import com.leyou.item.service.GoodsService;
import com.leyou.item.vo.SpuVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    @Transactional
    public PageResult<SpuVo> querySpuBoByPage(String key, Boolean saleable, Integer page, Integer rows) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 搜索条件
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("title", "%" + key + "%");
        }
        if(saleable != null){
            criteria.andEqualTo("saleable", saleable);
        }
        // 分页条件
        if(page != null && page.intValue() > 0 && rows.intValue() > 0){
            PageHelper.startPage(page, rows);
        }
        // 执行查询
        List<Spu> spus = this.spuMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(spus)){
            throw new LyException(ExceptionEnum.SPU_NOT_FOUNT);
        }
        PageInfo<Spu> spuPageInfo = new PageInfo<>(spus);

        // 查询分类名（数据库保存是商品分类是cid1, cid2, cid3）
        List<SpuVo> spuVos = new ArrayList<>();
        spus.forEach(spu -> {
            SpuVo spuVo = new SpuVo();
            // copy共同属性的值到新的对象
            BeanUtils.copyProperties(spu, spuVo);
            // 查询分类名称
            List<String> names = this.categoryService
                    .queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuVo.setCname(StringUtils.join(names, "/"));
            // 查询品牌的名称
            spuVo.setBname(this.brandMapper.selectByPrimaryKey(spu.getBrandId()).getName());
            spuVos.add(spuVo);
        });
        return new PageResult<>(spuPageInfo.getTotal(), spuPageInfo.getPages(), spuVos);
    }

    @Override
    @Transactional
    public void saveGoods(SpuVo spuVo) {
        // 新增spu
        spuVo.setId(null);
        spuVo.setSaleable(true);
        spuVo.setValid(true);
        spuVo.setCreateTime(new Date());
        spuVo.setLastUpdateTime(spuVo.getCreateTime());
        int count = this.spuMapper.insertSelective(spuVo);
        if(count <= 0){
            throw new LyException(ExceptionEnum.SPU_ADD_FAIL);
        }

        // 新增spuDetail
        SpuDetail spuDetail = spuVo.getSpuDetail();
        if(spuDetail != null){
            spuDetail.setSpuId(spuVo.getId());
            count = this.spuDetailMapper.insertSelective(spuDetail);
            if(count <= 0){
                throw new LyException(ExceptionEnum.SPUDETAIL_ADD_FAIL);
            }
        }else {
            throw new LyException(ExceptionEnum.SPUDETAIL_NOT_FOUNT);
        }

        // 保存sku与库存
        saveSkuAndStock(spuVo);

        // 发送MQ消息
        this.sendMessage(spuVo.getId(), "insert");
    }

    private void saveSkuAndStock(SpuVo spuVo) {
        spuVo.getSkus().forEach(sku -> {
            // 新增sku
            sku.setSpuId(spuVo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            int count = this.skuMapper.insertSelective(sku);
            if(count <= 0){
                throw new LyException(ExceptionEnum.SKU_ADD_FAIL);
            }

            // 新增库存
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            count = this.stockMapper.insertSelective(stock);
            if(count <= 0){
                throw new LyException(ExceptionEnum.STOCK_ADD_FAIL);
            }
        });
    }

    @Override
    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        SpuDetail spuDetail = this.spuDetailMapper.selectByPrimaryKey(spuId);
        if(spuDetail == null){
            throw new LyException(ExceptionEnum.SPUDETAIL_NOT_FOUNT);
        }
        return spuDetail;
    }

    @Override
    public List<Sku> querySkuBySpuId(Long spuId) {
        if(spuId == null || spuId.intValue() <= 0){
            throw new LyException(ExceptionEnum.PARAMETERS_ILLEGAL_OR_NULL);
        }
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = this.skuMapper.select(sku);
        skus.forEach(s -> {
            Stock stock = this.stockMapper.selectByPrimaryKey(s.getId());
            s.setStock(stock.getStock());
        });
        if(CollectionUtils.isEmpty(skus)){
            throw new LyException(ExceptionEnum.SKU_NOT_FOUNT);
        }
        return skus;
    }

    @Override
    @Transactional
    public void updateGoods(SpuVo spuVo) {

        // 删除以前的sku以及库存
        this.deleteSkuAndStock(spuVo.getId());

        // 新增sku和库存
        saveSkuAndStock(spuVo);

        // 更新spu
        spuVo.setLastUpdateTime(new Date());
        this.spuMapper.updateByPrimaryKeySelective(spuVo);

        // 更新spu详情
        this.spuDetailMapper.updateByPrimaryKeySelective(spuVo.getSpuDetail());

        // 发送MQ消息
        this.sendMessage(spuVo.getId(), "update");
    }

    @Override
    public void removalGoods(Long spuId, Boolean saleable) {
        if(spuId == null || spuId.intValue() <= 0 || saleable == null){
            throw new LyException(ExceptionEnum.PARAMETERS_ILLEGAL_OR_NULL);
        }
        Integer status = saleable == true ? 0 : 1;
        int count = this.spuMapper.updateGoodStatus(spuId, status);
        if(count <= 0){
            throw new LyException(ExceptionEnum.SPU_SALEABLE_UPDATE_FAIL);
        }
    }

    private void deleteSkuAndStock(Long spuId){
        // 查询以前的sku
        List<Sku> skus = this.querySkuBySpuId(spuId);
        // 如果以前存在，则删除
        if(!CollectionUtils.isEmpty(skus)){
            List<Long> ids = skus.stream().map(Sku::getId).collect(Collectors.toList());
            // 删除以前的库存
            Example example = new Example(Stock.class);
            example.createCriteria().andIn("skuId", ids);
            this.stockMapper.deleteByExample(example);

            Sku sku = new Sku();
            sku.setSpuId(spuId);
            // 删除以前的sku
            this.skuMapper.delete(sku);
        }
    }

    @Override
    @Transactional
    public void deleteGoods(Long spuId) {
        // 删除spu
        int count = this.spuMapper.deleteByPrimaryKey(spuId);
        // 删除spu详情
        count = this.spuDetailMapper.deleteByPrimaryKey(spuId);
        if(count <= 0){
            throw new LyException(ExceptionEnum.SPU_DELETE_FAIL);
        }
        // 删除sku以及库存
        this.deleteSkuAndStock(spuId);

        this.sendMessage(spuId, "delete");
    }

    @Override
    public Spu querySpuById(Long id) {
        Spu spu = this.spuMapper.selectByPrimaryKey(id);
        if(spu == null){
            throw new LyException(ExceptionEnum.SPU_NOT_FOUNT);
        }
        spu.setSkuList(this.querySkuBySpuId(id));
        spu.setSpuDetail(this.querySpuDetailBySpuId(id));
        return spu;
    }

    /**
     * 这里没有指定交换机
     * 因此默认发送到了配置中的：`leyou.item.exchange`
     * @param id
     * @param type
     */
    private void sendMessage(Long id, String type){
        // 发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            log.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }

    @Override
    public Sku querySkuById(Long id) {
        Sku sku = this.skuMapper.selectByPrimaryKey(id);
        if(sku == null){
            throw new LyException(ExceptionEnum.SKU_NOT_FOUNT);
        }
        return sku;
    }
}
